package com.shebei.api.equipment_api_test.http;


import com.shebei.api.equipment_api_test.http.httpdeletejson.HttpDeleteWithBody;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class HttpClientDeleteJson implements HttpClienInterface {


    @Override
    public String sendRequest(String url, String requestBody, Map<String, String> head) {



      String response=  doDelete( url, requestBody, head);
        return response;
    }

    private   String doDelete(String url, String json,Map<String, String> head) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {




            // 创建http
            HttpDeleteWithBody httpDelete = new  HttpDeleteWithBody(url);


            if (head != null){
                for (String key : head.keySet()) {
                    httpDelete.setHeader(key,String.valueOf(head.get(key)));
                }

                httpDelete.addHeader("content-type", "application/json");
            }
            if(json!=null){

                StringEntity entity = new StringEntity(json.toString(), ContentType.APPLICATION_JSON);
                httpDelete.setEntity(entity);
            }



            // 执行请求
            response = httpclient.execute(httpDelete);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }


}

